# src/main.py
from flask import Flask, request, jsonify
from src.services.auth_service import AuthService
from src.utils.response import ResponseUtil

app = Flask(__name__)

# 手动添加CORS支持，避免使用外部依赖
@app.after_request
def add_cors_headers(response):
    # 允许所有来源访问
    response.headers['Access-Control-Allow-Origin'] = '*'
    # 允许的请求方法
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    # 允许的请求头
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    # 允许发送Cookie
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response

# 初始化认证服务
auth_service = AuthService()

@app.route('/api/login', methods=['POST'])
def login():
    """登录接口"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return ResponseUtil.error(1007, "请求数据格式错误")

        # 同时支持account和username参数
        account = data.get('account') or data.get('username')
        password = data.get('password')

        # 执行登录
        user_info = auth_service.login(account, password)

        # 返回成功响应
        return ResponseUtil.success(user_info, "登录成功")

    except Exception as e:
        # 异常处理
        return ResponseUtil.error(1008, str(e))

# 健康检查接口
@app.route('/health', methods=['GET'])
def health():
    return ResponseUtil.success(None, "服务正常运行")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=9000)
